package com.xucia.jsponic.data;

import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeSet;

import org.mozilla.javascript.NativeObject;

import com.xucia.jsponic.rpc.RPCall;

/**
 * @author Kris Zyp
 *
 */
public class MonitoredContent extends NativeObject implements PropertyChangeListener{
	@Override
	public void propertyChange(PropertyChangeEvent propertyChangeEvent) {
		Persistable object = (Persistable) propertyChangeEvent.getSource();
		ChangeStamp change = objectsChange.get(object);
		if (change == null) {
			change = new ChangeStamp();
			change.object = (Persistable) propertyChangeEvent.getSource();
			objectsChange.put(object,change);
		}
		else
			changedObjects.remove(change);
		change.time = new Date().getTime();
		changedObjects.add(change);
	}
	public static class ChangeStamp {
		Persistable object;
		long time;
		public int compareTo(Object o) {
			if (time > ((ChangeStamp)o).time)
				return 1;
			else if (time == ((ChangeStamp)o).time)
				return 0;
			else 
				return -1;
		}
	}
	Set<ChangeStamp> changedObjects = new TreeSet();
	Map<Persistable,ChangeStamp> objectsChange = new HashMap();
	public List<RPCall> getMessagesSince(long time) {
		List<RPCall> messages = new ArrayList();
		for (ChangeStamp change : changedObjects) {
			if (change.time < time)
				return messages;
			RPCall message = new RPCall(this,"changed",new Object[] { change.object });
			messages.add(message);
		}
		return messages;
	}
	
}
